from flask import Flask, render_template, request, jsonify
import database
import os, json

app = Flask(__name__, static_folder='./node_modules')


def createBase():
    base = database.Base(os.path.join(os.getcwd(), 'task.db'))
    try:
        base.createTable(
            'task', 'id INT, task TEXT, time TEXT')
        base.createTable(
            'history', 'id INT, task TEXT, time TEXT')
    except:
        pass
    return base


@app.route('/home')
@app.route('/')
def root_get():
    base = createBase()
    message = []
    infos = base.findAll('task')
    for info in infos:
        message.append({
            'num': info[0],
            'task': info[1],
            'time': info[2]
        })
    return render_template('index.html', items=message)


@app.route('/history')
def history_get():
    base = createBase()
    message = []
    infos = base.findAll('history')
    for info in infos:
        message.append({
            'num': info[0],
            'task': info[1],
            'time': info[2]
        })
    return render_template('history.html', items=message)


@app.route('/finish', methods=['POST'])
def finish_post():
    try:
        num = request.form['num']
        print(num)
        base = createBase()
        infos = base.findAll('task')
        for i in range(len(num)):
            base.deleteFrom('task', 'id=%s' % num[i])
            base.insertTo('history', '"{0}","{1}","{2}"'.format(
                len(base.findAll('history'))+1, infos[int(num[i])-1][1], infos[int(num[i])-1][2])
            )
        infos = base.findAll('task')
        for i in infos:
            who = 'task = "{}"'.format(i[1])
            example = 'id = {}'.format(str(infos.index(i)+1))
            base.updateTo('task', who, example)
        return 'success'
    except Exception as e:
        print(e)
        return 'fail'


@app.route('/remove', methods=['GET', 'POST'])
def remove_url():
    if request.method == 'GET':
        base = createBase()
        message = []
        names = []
        infos = base.findAll('task')
        for info in infos:
            message.append({
                'num': info[0],
                'task': info[1],
                'time': info[2]
            })
            names.append(info[1])
        template = render_template('remove.html', items=message, names=names)
        return template
    else:
        try:
            num = request.form['num']
            base = createBase()
            for i in range(len(num)):
                base.deleteFrom('task', 'id=%s' % num[i])
            infos = base.findAll('task')
            for i in infos:
                who = 'task = "{}"'.format(i[1])
                example = 'id = {}'.format(str(infos.index(i)+1))
                base.updateTo('task', who, example)
            return 'success'
        except Exception as e:
            print(e)
            return 'fail'


@app.route('/release', methods=['GET', 'POST'])
def release_url():
    if request.method == 'GET':
        template = render_template('release.html')
        return template
    else:
        data = request.form
        base = createBase()
        tasks = json.loads(data['task'])
        dtime = data['time']
        baseLen = len(base.findAll('task'))+1
        try:
            for i in tasks:
                print(i)
                base.insertTo('task', '"{0}","{1}","{2}"'.format(
                    str(baseLen), i, dtime))
                baseLen = baseLen+1
            return 'success'
        except Exception as e:
            print(e)
            return 'fail'


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5050)
